<template>
  <div class="billing-method-page">
    <!-- 暂未关联物业公司提示 -->
    <NoPropertyCompany 
      v-if="!hasPropertyCompanies" 
      title="暂未关联物业公司"
      description="您当前暂未关联任何物业公司，无法进行计费方式管理"
      icon="House"
      :show-contact-tip="true"
      :show-actions="true"
      :show-refresh-button="true"
      :show-contact-button="false"
      refresh-button-text="刷新页面"
      @refresh="loadPropertyCompanies"
    />

    <!-- 物业公司选择区域 -->
    <el-card v-else class="company-selection-card" shadow="never">
      <div class="company-selection-content">
        <div class="selection-header">
          <span class="card-title">选择物业公司</span>
          <el-tag v-if="selectedCompanies.length > 0" type="success" size="small">
            已选择 {{ selectedCompanies.length }} 个物业公司
          </el-tag>
        </div>
        <el-checkbox-group v-model="selectedCompanies" @change="handleCompanySelectionChange">
          <el-checkbox 
            v-for="company in propertyCompanies"
            :key="company.propertyCompanyId"
            :value="company.propertyCompanyId"
            class="company-checkbox"
          >
            {{ company.propertyCompanyName }} (ID: {{ company.propertyCompanyId }})
          </el-checkbox>
        </el-checkbox-group>
        <div class="form-tip">
          <el-icon><InfoFilled /></el-icon>
          <span>支持多选，选中的物业公司将共享相同的计费方式配置</span>
        </div>
      </div>
    </el-card>

    <!-- 计费方式配置区域 -->
    <div v-if="selectedCompanies.length > 0" class="billing-config-section">
      <!-- Tab标签页 -->
      <el-card class="tab-card" shadow="never">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card">
          <el-tab-pane label="物业费" name="property">
            <div class="tab-content">
              <div class="tab-header">
                <h3>物业费计费方式</h3>
              </div>
              <!-- 多公司计费方式显示 -->
              <div v-if="selectedCompanies.length > 1" class="multi-company-section">
                <div 
                  v-for="companyId in selectedCompanies" 
                  :key="companyId"
                  class="company-billing-section"
                >
                  <div class="company-header">
                    <h4>{{ getCompanyName(companyId) }}</h4>
                    <el-tag type="info" size="small">物业公司</el-tag>
                    <el-button type="primary" size="small" @click="handleAddBillingMethod('property', companyId)">
                      <el-icon><Plus /></el-icon>
                      新增计费方式
                    </el-button>
                  </div>
                  <BillingMethodTable 
                    :data="getCompanyBillingMethods(companyId, 'property')" 
                    :loading="tabLoadingStates.property"
                    @edit="(row) => handleEdit(row, companyId)"
                    @delete="(row) => handleDelete(row, companyId)"
                  />
                </div>
              </div>
              <!-- 单公司计费方式显示 -->
              <div v-else class="single-company-section">
                <div class="single-company-header">
                  <el-button type="primary" @click="handleAddBillingMethod('property', selectedCompanies[0])">
                    <el-icon><Plus /></el-icon>
                    新增计费方式
                  </el-button>
                </div>
                <BillingMethodTable 
                  :data="propertyFeeMethods" 
                  :loading="tabLoadingStates.property"
                  @edit="handleEdit"
                  @delete="handleDelete"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="卫生费" name="sanitation">
            <div class="tab-content">
              <div class="tab-header">
                <h3>卫生费计费方式</h3>
              </div>
              <!-- 多公司计费方式显示 -->
              <div v-if="selectedCompanies.length > 1" class="multi-company-section">
                <div 
                  v-for="companyId in selectedCompanies" 
                  :key="companyId"
                  class="company-billing-section"
                >
                  <div class="company-header">
                    <h4>{{ getCompanyName(companyId) }}</h4>
                    <el-tag type="info" size="small">物业公司</el-tag>
                    <el-button type="primary" size="small" @click="handleAddBillingMethod('sanitation', companyId)">
                      <el-icon><Plus /></el-icon>
                      新增计费方式
                    </el-button>
                  </div>
                  <BillingMethodTable 
                    :data="getCompanyBillingMethods(companyId, 'sanitation')" 
                    :loading="tabLoadingStates.sanitation"
                    @edit="(row) => handleEdit(row, companyId)"
                    @delete="(row) => handleDelete(row, companyId)"
                  />
                </div>
              </div>
              <!-- 单公司计费方式显示 -->
              <div v-else class="single-company-section">
                <div class="single-company-header">
                  <el-button type="primary" @click="handleAddBillingMethod('sanitation', selectedCompanies[0])">
                    <el-icon><Plus /></el-icon>
                    新增计费方式
                  </el-button>
                </div>
                <BillingMethodTable 
                  :data="sanitationFeeMethods" 
                  :loading="tabLoadingStates.sanitation"
                  @edit="handleEdit"
                  @delete="handleDelete"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="燃气费" name="gas">
            <div class="tab-content">
              <div class="tab-header">
                <h3>燃气费计费方式</h3>
              </div>
              <!-- 多公司计费方式显示 -->
              <div v-if="selectedCompanies.length > 1" class="multi-company-section">
                <div 
                  v-for="companyId in selectedCompanies" 
                  :key="companyId"
                  class="company-billing-section"
                >
                  <div class="company-header">
                    <h4>{{ getCompanyName(companyId) }}</h4>
                    <el-tag type="info" size="small">物业公司</el-tag>
                    <el-button type="primary" size="small" @click="handleAddBillingMethod('gas', companyId)">
                      <el-icon><Plus /></el-icon>
                      新增计费方式
                    </el-button>
                  </div>
                  <BillingMethodTable 
                    :data="getCompanyBillingMethods(companyId, 'gas')" 
                    :loading="tabLoadingStates.gas"
                    @edit="(row) => handleEdit(row, companyId)"
                    @delete="(row) => handleDelete(row, companyId)"
                  />
                </div>
              </div>
              <!-- 单公司计费方式显示 -->
              <div v-else class="single-company-section">
                <div class="single-company-header">
                  <el-button type="primary" @click="handleAddBillingMethod('gas', selectedCompanies[0])">
                    <el-icon><Plus /></el-icon>
                    新增计费方式
                  </el-button>
                </div>
                <BillingMethodTable 
                  :data="gasFeeMethods" 
                  :loading="tabLoadingStates.gas"
                  @edit="handleEdit"
                  @delete="handleDelete"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="水费" name="water">
            <div class="tab-content">
              <div class="tab-header">
                <h3>水费计费方式</h3>
              </div>
              <!-- 多公司计费方式显示 -->
              <div v-if="selectedCompanies.length > 1" class="multi-company-section">
                <div 
                  v-for="companyId in selectedCompanies" 
                  :key="companyId"
                  class="company-billing-section"
                >
                  <div class="company-header">
                    <h4>{{ getCompanyName(companyId) }}</h4>
                    <el-tag type="info" size="small">物业公司</el-tag>
                    <el-button type="primary" size="small" @click="handleAddBillingMethod('water', companyId)">
                      <el-icon><Plus /></el-icon>
                      新增计费方式
                    </el-button>
                  </div>
                  <BillingMethodTable 
                    :data="getCompanyBillingMethods(companyId, 'water')" 
                    :loading="tabLoadingStates.water"
                    @edit="(row) => handleEdit(row, companyId)"
                    @delete="(row) => handleDelete(row, companyId)"
                  />
                </div>
              </div>
              <!-- 单公司计费方式显示 -->
              <div v-else class="single-company-section">
                <div class="single-company-header">
                  <el-button type="primary" @click="handleAddBillingMethod('water', selectedCompanies[0])">
                    <el-icon><Plus /></el-icon>
                    新增计费方式
                  </el-button>
                </div>
                <BillingMethodTable 
                  :data="waterFeeMethods" 
                  :loading="tabLoadingStates.water"
                  @edit="handleEdit"
                  @delete="handleDelete"
                />
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="电费" name="electricity">
            <div class="tab-content">
              <div class="tab-header">
                <h3>电费计费方式</h3>
              </div>
              <!-- 多公司计费方式显示 -->
              <div v-if="selectedCompanies.length > 1" class="multi-company-section">
                <div 
                  v-for="companyId in selectedCompanies" 
                  :key="companyId"
                  class="company-billing-section"
                >
                  <div class="company-header">
                    <h4>{{ getCompanyName(companyId) }}</h4>
                    <el-tag type="info" size="small">物业公司</el-tag>
                    <el-button type="primary" size="small" @click="handleAddBillingMethod('electricity', companyId)">
                      <el-icon><Plus /></el-icon>
                      新增计费方式
                    </el-button>
                  </div>
                  <BillingMethodTable 
                    :data="getCompanyBillingMethods(companyId, 'electricity')" 
                    :loading="tabLoadingStates.electricity"
                    @edit="(row) => handleEdit(row, companyId)"
                    @delete="(row) => handleDelete(row, companyId)"
                  />
                </div>
              </div>
              <!-- 单公司计费方式显示 -->
              <div v-else class="single-company-section">
                <div class="single-company-header">
                  <el-button type="primary" @click="handleAddBillingMethod('electricity', selectedCompanies[0])">
                    <el-icon><Plus /></el-icon>
                    新增计费方式
                  </el-button>
                </div>
                <BillingMethodTable 
                  :data="electricityFeeMethods" 
                  :loading="tabLoadingStates.electricity"
                  @edit="handleEdit"
                  @delete="handleDelete"
                />
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 计费方式编辑对话框 -->
    <BillingMethodDialog
      v-model="dialogVisible"
      :billing-method="currentBillingMethod"
      :fee-type="activeTab"
      :selected-company-id="selectedCompanies[0]"
      :selected-company-name="getCompanyName(selectedCompanies[0])"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, InfoFilled } from '@element-plus/icons-vue'
import NoPropertyCompany from '@/components/NoPropertyCompany/index.vue'
import BillingMethodTable from './components/BillingMethodTable.vue'
import BillingMethodDialog from '@/views/property/components/BillingMethodDialog.vue'
import { propertyCompanyApi } from '@/api/property/propertyCompany'

// 导入API
import { billingMethodApi } from '@/api/property/billingMethod'
import { buildingTypeApi } from '@/api/buildingType'

// 响应式数据
const loading = ref(false)
const hasPropertyCompanies = ref(false)
const propertyCompanies = ref<any[]>([])
const selectedCompanies = ref<number[]>([])
const activeTab = ref('property')
const dialogVisible = ref(false)
const currentBillingMethod = ref<any>(null)

// Tab级别的加载状态
const tabLoadingStates = ref({
  property: false,
  sanitation: false,
  gas: false,
  water: false,
  electricity: false
})

// 模拟三个物业公司数据
const mockPropertyCompanies = [
  {
    propertyCompanyId: 1001,
    propertyCompanyName: '阳光物业有限公司',
    propertyCompanyCode: 'YG001',
    status: 1
  },
  {
    propertyCompanyId: 1002,
    propertyCompanyName: '绿城物业服务集团',
    propertyCompanyCode: 'LC002',
    status: 1
  },
  {
    propertyCompanyId: 1003,
    propertyCompanyName: '万科物业服务有限公司',
    propertyCompanyCode: 'WK003',
    status: 1
  }
]

// 多公司计费方式数据结构
const multiCompanyBillingMethods = ref<Record<number, {
  property: any[]
  sanitation: any[]
  gas: any[]
  water: any[]
  electricity: any[]
}>>({})

// 单公司计费方式数据
const propertyFeeMethods = ref<any[]>([])
const sanitationFeeMethods = ref<any[]>([])
const gasFeeMethods = ref<any[]>([])
const waterFeeMethods = ref<any[]>([])
const electricityFeeMethods = ref<any[]>([])

// 计算属性
const currentFeeMethods = computed(() => {
  switch (activeTab.value) {
    case 'property':
      return propertyFeeMethods.value
    case 'sanitation':
      return sanitationFeeMethods.value
    case 'gas':
      return gasFeeMethods.value
    case 'water':
      return waterFeeMethods.value
    case 'electricity':
      return electricityFeeMethods.value
    default:
      return []
  }
})

// 获取公司名称
const getCompanyName = (companyId: number): string => {
  const company = mockPropertyCompanies.find(c => c.propertyCompanyId === companyId)
  return company ? company.propertyCompanyName : `公司${companyId}`
}

// 获取指定公司的计费方式数据
const getCompanyBillingMethods = (companyId: number, feeType: string) => {
  const companyData = multiCompanyBillingMethods.value[companyId]
  if (!companyData) return []
  
  switch (feeType) {
    case 'property':
      return companyData.property
    case 'sanitation':
      return companyData.sanitation
    case 'gas':
      return companyData.gas
    case 'water':
      return companyData.water
    case 'electricity':
      return companyData.electricity
    default:
      return []
  }
}

// 方法
// 获取物业公司列表
const loadPropertyCompanies = async () => {
  try {
    loading.value = true
    
    // 先尝试调用API
    try {
      const response = await buildingTypeApi.getUserPropertyCompanies()
      if (response.code === 200) {
        propertyCompanies.value = response.data || []
        hasPropertyCompanies.value = propertyCompanies.value.length > 0
        
        // 默认选中第一个公司
        if (propertyCompanies.value.length > 0) {
          selectedCompanies.value = [propertyCompanies.value[0].propertyCompanyId]
          // 只加载默认Tab（物业费）的计费方式数据
          await loadBillingMethodsForCompany(propertyCompanies.value[0].propertyCompanyId)
        }
        return
      }
    } catch (apiError) {
      console.warn('API调用失败，使用模拟数据:', apiError)
    }
    
    // 如果API调用失败，使用模拟数据
    propertyCompanies.value = mockPropertyCompanies
    hasPropertyCompanies.value = propertyCompanies.value.length > 0
    
    // 默认选中第一个公司
    if (propertyCompanies.value.length > 0) {
      selectedCompanies.value = [propertyCompanies.value[0].propertyCompanyId]
    }
  } catch (error) {
    console.error('加载物业公司失败:', error)
    ElMessage.error('加载物业公司失败')
    propertyCompanies.value = []
    hasPropertyCompanies.value = false
  } finally {
    loading.value = false
  }
}

// 为指定公司加载计费方式数据
const loadBillingMethodsForCompany = async (propertyCompanyId: number) => {
  try {
    // 设置当前Tab的加载状态
    const currentFeeType = activeTab.value
    tabLoadingStates.value[currentFeeType] = true
    
    try {
      const response = await billingMethodApi.getBillingMethodList({
        propertyCompanyId,
        feeType: currentFeeType
      })
      
      if (response.code === 200) {
        const methods = response.data || []
        
        // 更新对应费用类型的数据
        switch (currentFeeType) {
          case 'property':
            propertyFeeMethods.value = methods
            break
          case 'sanitation':
            sanitationFeeMethods.value = methods
            break
          case 'gas':
            gasFeeMethods.value = methods
            break
          case 'water':
            waterFeeMethods.value = methods
            break
          case 'electricity':
            electricityFeeMethods.value = methods
            break
        }
        
        // 更新多公司数据结构
        if (!multiCompanyBillingMethods.value[propertyCompanyId]) {
          multiCompanyBillingMethods.value[propertyCompanyId] = {
            property: [],
            sanitation: [],
            gas: [],
            water: [],
            electricity: []
          }
        }
        multiCompanyBillingMethods.value[propertyCompanyId][currentFeeType] = methods
        
        console.log(`已加载${currentFeeType}计费方式数据，数量:`, methods.length)
      }
    } catch (error) {
      console.error(`加载${currentFeeType}计费方式失败:`, error)
      ElMessage.error(`加载${getFeeTypeLabel(currentFeeType)}计费方式失败`)
    }
  } catch (error) {
    console.error('加载计费方式数据失败:', error)
    ElMessage.error('加载计费方式数据失败')
  } finally {
    // 清除当前Tab的加载状态
    const currentFeeType = activeTab.value
    tabLoadingStates.value[currentFeeType] = false
  }
}

// 获取费用类型标签
const getFeeTypeLabel = (feeType: string): string => {
  const feeTypeMap: Record<string, string> = {
    property: '物业费',
    sanitation: '卫生费',
    gas: '燃气费',
    water: '水费',
    electricity: '电费'
  }
  return feeTypeMap[feeType] || feeType
}

const handleCompanySelectionChange = async (companies: number[]) => {
  selectedCompanies.value = companies
  console.log('选中的物业公司:', companies)
  
  if (companies.length === 0) {
    // 清空所有数据
    propertyFeeMethods.value = []
    sanitationFeeMethods.value = []
    gasFeeMethods.value = []
    waterFeeMethods.value = []
    electricityFeeMethods.value = []
    multiCompanyBillingMethods.value = {}
    return
  }
  
  // 如果选中多个公司，只加载当前激活Tab的计费方式数据
  if (companies.length > 1) {
    try {
      // 为每个选中的公司加载当前Tab的计费方式数据
      for (const companyId of companies) {
        const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === companyId)
        if (!selectedCompany) {
          console.warn(`未找到物业公司信息，ID: ${companyId}`)
          continue
        }
        
        await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
      }
    } catch (error) {
      console.error('加载多公司计费方式数据失败:', error)
      ElMessage.error('加载计费方式数据失败')
    }
  }
  // 如果只选中一个公司，只加载当前激活Tab的计费方式数据
  else if (companies.length === 1) {
    const companyId = companies[0]
    const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === companyId)
    if (selectedCompany) {
      await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
    }
  }
}

const handleTabClick = (tab: any) => {
  console.log('Tab点击事件触发，tab对象:', tab)
  console.log('当前激活的Tab:', activeTab.value)
  
  // Tab切换和数据加载现在由watch监听器处理
  // 这里只记录点击事件，不做其他处理
}

// 检查是否需要为指定Tab加载数据
const shouldLoadDataForTab = (tabName: string): boolean => {
  if (selectedCompanies.value.length === 0) {
    return false
  }
  
  // 检查当前Tab的数据是否已经加载
  if (selectedCompanies.value.length === 1) {
    // 单公司模式
    const companyId = selectedCompanies.value[0]
    const companyData = multiCompanyBillingMethods.value[companyId]
    
    if (!companyData || !companyData[tabName] || companyData[tabName].length === 0) {
      // 检查本地数据是否为空
      switch (tabName) {
        case 'property':
          return propertyFeeMethods.value.length === 0
        case 'sanitation':
          return sanitationFeeMethods.value.length === 0
        case 'gas':
          return gasFeeMethods.value.length === 0
        case 'water':
          return waterFeeMethods.value.length === 0
        case 'electricity':
          return electricityFeeMethods.value.length === 0
        default:
          return true
      }
    }
  } else {
    // 多公司模式
    for (const companyId of selectedCompanies.value) {
      const companyData = multiCompanyBillingMethods.value[companyId]
      if (!companyData || !companyData[tabName] || companyData[tabName].length === 0) {
        return true
      }
    }
  }
  
  return false
}

const handleAddBillingMethod = (feeType: string, companyId?: number) => {
  currentBillingMethod.value = null
  dialogVisible.value = true
  // 如果是多公司模式，需要传递公司ID
  if (companyId) {
    currentBillingMethod.value = { feeType, companyId }
  }
}

const handleEdit = async (row: any, companyId?: number) => {
  try {
    console.log('开始编辑计费方式，行数据:', row, '公司ID:', companyId)
    
    // 编辑时调用详情接口获取完整数据
    const response = await billingMethodApi.getBillingMethodDetail(row.id)
    if (response.code === 200) {
      console.log('获取计费方式详情成功:', response.data)
      
      // 确保数据格式正确
      const billingMethodData = { ...response.data }
      
      // 确保计费类型是数字
      if (billingMethodData.methodType !== undefined && billingMethodData.methodType !== null) {
        billingMethodData.methodType = Number(billingMethodData.methodType)
      }
      
      // 确保其他数值字段也是正确的类型
      if (billingMethodData.unitPrice !== undefined && billingMethodData.unitPrice !== null) {
        billingMethodData.unitPrice = Number(billingMethodData.unitPrice)
      }
      if (billingMethodData.fixedAmount !== undefined && billingMethodData.fixedAmount !== null) {
        billingMethodData.fixedAmount = Number(billingMethodData.fixedAmount)
      }
      if (billingMethodData.status !== undefined && billingMethodData.status !== null) {
        billingMethodData.status = Number(billingMethodData.status)
      }
      if (billingMethodData.sortOrder !== undefined && billingMethodData.sortOrder !== null) {
        billingMethodData.sortOrder = Number(billingMethodData.sortOrder)
      }
      
      // 设置公司ID
      if (companyId) {
        billingMethodData.companyId = companyId
      }
      
      console.log('处理后的计费方式数据:', billingMethodData)
      
      currentBillingMethod.value = billingMethodData
      dialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取计费方式详情失败')
    }
  } catch (error) {
    console.error('获取计费方式详情失败:', error)
    ElMessage.error('获取计费方式详情失败')
  }
}

const handleDelete = async (row: any, companyId?: number) => {
  try {
    const companyName = companyId ? getCompanyName(companyId) : ''
    const confirmMessage = companyId 
      ? `确定要删除"${companyName}"的计费方式"${row.methodName}"吗？`
      : `确定要删除计费方式"${row.methodName}"吗？`
    
    await ElMessageBox.confirm(
      confirmMessage,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    const response = await billingMethodApi.deleteBillingMethod(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      
      // 重新加载数据
      if (companyId) {
        await loadBillingMethodsForCompany(companyId)
      } else if (selectedCompanies.value.length === 1) {
        const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === selectedCompanies.value[0])
        if (selectedCompany) {
          await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
        }
      }
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除计费方式失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleDialogConfirm = async (data: any) => {
  try {
    console.log('保存计费方式:', data)
    
    // 确定物业公司ID
    let propertyCompanyId: number
    if (data.propertyCompanyId) {
      propertyCompanyId = data.propertyCompanyId
    } else if (selectedCompanies.value.length === 1) {
      const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === selectedCompanies.value[0])
      propertyCompanyId = selectedCompany?.propertyCompanyId || 0
    } else {
      ElMessage.error('请选择物业公司')
      return
    }
    
    // 准备请求数据
    const requestData = {
      ...data,
      propertyCompanyId,
      feeType: activeTab.value
    }
    
    let response
    if (data.id) {
      // 编辑
      response = await billingMethodApi.updateBillingMethod(requestData)
    } else {
      // 新增
      response = await billingMethodApi.createBillingMethod(requestData)
    }
    
    if (response.code === 200) {
      ElMessage.success(data.id ? '更新成功' : '创建成功')
      dialogVisible.value = false
      
      // 重新加载数据
      await loadBillingMethodsForCompany(propertyCompanyId)
    } else {
      ElMessage.error(response.message || (data.id ? '更新失败' : '创建失败'))
    }
  } catch (error) {
    console.error('保存计费方式失败:', error)
    ElMessage.error('保存失败')
  }
}

// 生命周期
onMounted(() => {
  loadPropertyCompanies()
})

// 监听activeTab变化，处理Tab切换时的数据加载
watch(activeTab, async (newTab, oldTab) => {
  console.log('Tab切换监听触发:', { oldTab, newTab })
  
  if (newTab && newTab !== oldTab && selectedCompanies.value.length > 0) {
    // 检查是否需要加载数据
    const needLoadData = shouldLoadDataForTab(newTab)
    
    if (needLoadData) {
      console.log(`监听器：开始加载${newTab}计费方式数据...`)
      
      // 如果是多公司模式，为所有选中的公司加载数据
      if (selectedCompanies.value.length > 1) {
        for (const companyId of selectedCompanies.value) {
          const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === companyId)
          if (selectedCompany) {
            await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
          }
        }
      } else {
        // 单公司模式
        const companyId = selectedCompanies.value[0]
        const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === companyId)
        if (selectedCompany) {
          await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
        }
      }
    } else {
      console.log(`监听器：${newTab}Tab数据已加载，无需重新加载`)
    }
  }
})

// 重新加载计费方式数据的方法（用于删除后刷新）
const loadBillingMethods = async () => {
  if (selectedCompanies.value.length === 1) {
    const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === selectedCompanies.value[0])
    if (selectedCompany) {
      // 只重新加载当前激活Tab的数据
      await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
    }
  } else if (selectedCompanies.value.length > 1) {
    // 多公司模式，重新加载所有选中公司的当前Tab数据
    for (const companyId of selectedCompanies.value) {
      const selectedCompany = propertyCompanies.value.find(company => company.propertyCompanyId === companyId)
      if (selectedCompany) {
        await loadBillingMethodsForCompany(selectedCompany.propertyCompanyId)
      }
    }
  }
}
</script>

<style scoped>
.billing-method-page {
  padding: 20px;
}

.company-selection-card {
  margin-bottom: 20px;
}

.selection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.company-selection-content {
  padding: 20px;
}

.company-checkbox {
  margin-right: 20px;
  margin-bottom: 10px;
}

.form-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.billing-config-section {
  margin-top: 20px;
}

.tab-card {
  margin-bottom: 20px;
}

.tab-content {
  padding: 15px 0;
}

.tab-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.tab-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

/* 多公司显示样式 */
.multi-company-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.company-billing-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  background-color: #fafafa;
  position: relative;
}

.company-billing-section:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.company-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.company-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.company-header .el-tag {
  font-size: 12px;
}

.company-header .el-button {
  margin-left: auto;
}

/* 单公司显示样式 */
.single-company-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #e4e7ed;
}

.single-company-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 15px;
}
</style>
